import { defineStore } from "pinia";
import { ref, watch } from 'vue';

function initState() {
    return {
        isCollapse: false,
        tags: [
            {
                path: '/home',
                name: 'home',
                label: '首页',
                icon: 'home'
            }
        ],
        currentMenu: null,
        menuList: [],
        token: '',
        routerList: [],
    }
}
export const useAllDataStore = defineStore('allData', () => {
    const state = ref(initState())

    //监听state，对state进行持久化存储。这样页面刷新后也有数据
    watch(state, (newObj) => {
        if (!newObj.token) return;//只有退出才没有token，不用持久化存储
        localStorage.setItem("store", JSON.stringify(newObj))//有token时，状态（数据）都要持久化存储
    }, { deep: true }) // 要深度监听（因为state是用ref）

    //调整tags---若所选tag是首页，则不操作？？？；若所选tag不是首页，(如果tags里没有该tag的话)则往tags里面追加该tag
    function selectMenu(val) {
        if (val.name === 'home') {
            state.value.currentMenu = null;
        } else {
            state.value.currentMenu = val;
            let index = state.value.tags.findIndex((item) => item.name === val.name);
            index === -1 ? state.value.tags.push(val) : '';
        }
    }
    //删除tag---找到所要删除的tag在tags中的索引然后根据索引从tags中删除
    function updateTags(tag) {
        let index = state.value.tags.findIndex((item) => item.name === tag.name);
        state.value.tags.splice(index, 1);
    }
    //更新菜单menuList
    function updateMenuList(val) {
        state.value.menuList = val;
    }
    //实现动态路由
    function addMenu(router, type) {
        if (type === 'refresh') {
            //若本地已存储state，则获取过来用。？？？？？？？？？？？？？？这里不要太理解
            if (JSON.parse(localStorage.getItem("store"))) {
                state.value = JSON.parse(localStorage.getItem("store"));
                state.value.routerList = [];
            } else {
                return;
            }
        }
        const menu = state.value.menuList;
        const module = import.meta.glob("../views/**/*.vue");
        const routeArr = [];
        menu.forEach((item) => {
            if (item.children) {
                item.children.forEach((val) => {
                    let url = `../views/${val.url}.vue`;
                    val.component = module[url];
                    routeArr.push(...item.children);
                })
            } else {
                let url = `../views/${item.url}.vue`;
                item.component = module[url];
                routeArr.push(item);
            }
        })
        state.value.routerList = [];
        let routes = router.getRoutes();
        routes.forEach((item) => {
            if (item.name == "main" || item.name == "login" || item.name == "404") {
                return;
            } else {
                router.removeRoute(item.name);
            }
        })
        routeArr.forEach(item => {
            state.value.routerList.push(router.addRoute("main", item));
        })
    }
    //清除数据（退出登录时要调用）
    function clean() {
        state.value.routerList.forEach((item) => {
            if (item) item();//清除路由。item是路由，本身会返回一个removeRoute方法，去调用即可实现清除
        })
        //重置state数据
        state.value = initState()
        //删除本地缓存
        localStorage.removeItem("store")
    }
    return { state, selectMenu, updateTags, updateMenuList, addMenu, clean }
})